package com.novel.common.event;

import com.novel.service.UserService;
import com.novel.utils.FormatDateZone;
import com.novel.utils.GsonTool;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.Date;

@Slf4j
@Component
public class UserRecommendListener {

    @Autowired
    private UserService userService;

    @EventListener
    public void process(UserRecommendEvent event) {
        try {
            UserRecommendPojo pojo = event.getRecommendPojo();

            //计算需要增加多少推荐票
            if (pojo.getCost() < 50) {
                return;
            }

            log.info("事件监听成功！ 触发于:{} 触发事件:{}", event.getSource(), DateFormatUtils.format(event.getTimestamp(), FormatDateZone.Char_Millis_Seconds));
            //给用户增加推荐票
            boolean result = userService.addUserRecommend(Arrays.asList(pojo.getUserId()), pojo.getCost() / 50);
            //判断推荐票是否增加成功
            if (BooleanUtils.isFalse(result)) {
                log.error("赠送用户推荐票失败!请手动检查并赠送推荐票! 事件信息:{}", GsonTool.toJson(event));
            }
        } catch (Exception e) {
            log.error("监听器执行触发系统异常! 事件信息:{}", GsonTool.toJson(event), e);
        }
    }


}